<script setup lang="ts">
import { computed, reactive, shallowRef, watch } from 'vue';
import type { TreeOption } from 'naive-ui';
import { $t } from '@/locales';
import { fetchAddTenantModule, fetchGetAllModules, fetchGetTenantModuleIds } from '@/service/api';

defineOptions({
  name: 'TenantModuleAuthModal'
});

interface Props {
  // 租户 id
  tenantId: string;
}

const props = defineProps<Props>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const title = computed(() => $t('common.edit') + $t('page.system.tenant.moduleAuth'));

const tree = shallowRef<TreeOption[]>([]);

const checks = shallowRef<string[]>([]);

const model: Api.System.TenantModule = reactive(createDefaultModel());

function createDefaultModel(): Api.System.TenantModule {
  return {
    tenantId: props.tenantId,
    moduleIds: []
  };
}

async function getTree() {
  const { error, data } = await fetchGetAllModules();
  if (!error) {
    tree.value = data.map(recursive);
  }
}

async function getModuleIds() {
  const { error, data } = await fetchGetTenantModuleIds(props.tenantId);
  if (!error) {
    checks.value = data;
    getTree();
  }
}

/** recursive menu tree data, add prefix transform treeOption format */
function recursive(item: Api.System.Module): TreeOption {
  const result: TreeOption = {
    key: item.id,
    label: item.name
  };
  return result;
}

async function handleSubmit() {
  model.moduleIds = checks.value;
  const { error, data } = await fetchAddTenantModule(model);
  if (!error && data) {
    window.$message?.success?.($t('common.modifySuccess'));
    closeModal();
  }
}

function closeModal() {
  visible.value = false;
}

function init() {
  Object.assign(model, createDefaultModel());
  getModuleIds();
}

watch(visible, val => {
  if (val) {
    init();
  }
});
</script>

<template>
  <NModal v-model:show="visible" :title="title" preset="card" class="w-480px">
    <NTree v-model:checked-keys="checks" :data="tree" block-line expand-on-click checkable cascade virtual-scroll class="h-500px" />
    <template #footer>
      <NSpace justify="end">
        <NButton quaternary @click="closeModal">
          {{ $t('common.cancel') }}
        </NButton>
        <NButton type="primary" @click="handleSubmit">
          {{ $t('common.confirm') }}
        </NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
